/** @file error_console.cpp
    @brief Error console widget */
#include "error_console.h"

#include <Qt/qscrollbar.h>

ErrorConsole::ErrorConsole( QWidget *parent )
: QTextBrowser( parent ) {
    try {
        // Connect to the logger
        pm3::LOGGER::getSingleton().m_sig_report.Connect( this, &ErrorConsole::report );
    } catch ( ... ) {
        // Ignore
    }
}

void ErrorConsole::report( const std::string &r_section, const std::string &r_text ) {
    // Log all editor messages
    // Only log errors and warnings from other sections
    if (r_section != "Editor" && r_text.compare( 0, 3, "I: " ) == 0 )
        return;

    std::string text = r_text;

    // Start a table
    if (m_history.empty())
        m_history += "<table>\n";

    // An error?
    if ( r_text.compare( 0, 3, "E: " ) == 0 ) {
        m_history += "<tr style=\"color:#FF0000\">";
        m_history += std::string( "<td>" ) + r_text.substr( 0, 3 ) + "</td>";
        m_history += std::string( "<td>" ) + r_text.substr( 3, std::string::npos ) + "</td>";
        m_history += "</tr>\n";

    // A warning?
    } else if ( r_text.compare( 0, 3, "W: " ) == 0 ) {
        m_history += "<tr style=\"color:#FF6600\">";
        m_history += std::string( "<td>" ) + r_text.substr( 0, 3 ) + "</td>";
        m_history += std::string( "<td>" ) + r_text.substr( 3, std::string::npos ) + "</td>";
        m_history += "</tr>\n";

    // Just info
    } else {
        m_history += "<tr style=\"color:#0000FF\">";
        m_history += std::string( "<td>" ) + r_text.substr( 0, 3 ) + "</td>";
        m_history += std::string( "<td>" ) + r_text.substr( 3, std::string::npos ) + "</td>";
        m_history += "</tr>\n";
    }

    text = m_history + "\n</table>\n";

    // Set the text
    setHtml( text.c_str() );
    // Scroll to the last line
    verticalScrollBar()->setValue( verticalScrollBar()->maximum() );
}

